<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyDailyDeliveryReportCHModel;
use App\Remote\Guanyuan\GuanyuanRetry\GuanyuanRetryRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class SysGyDailyDeliveryReportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:gyDailyDeliveryReport';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 观远外卖日报表 -> clickhouse';

    public int $id;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        try {
            ini_set('memory_limit', '2G');
            $fields = [
                "dropType",
                "launchStartTime",
                "storeType",
                "storeName",
                "storeCode",
                "region",
                "date",
                "orderQuantity",
                "isItNewThisMonth",
                "dayLabor",
                "dailyEnergySource",
                "roi",
                "estimatedProfit",
                "durationOfOperationMonth",
                "openingHoursDays",
                "storeArea",
                "orderTurnover",
                "orderDiscountAmount",
                "actualAmountOfOrderReceived",
                "numberOfEmployees",
                "province",
                "city",
                "take_outOrderTurnover",
                "discountAmountForTakeoutOrders",
                "amountReceivedForTakeoutOrder",
                "tableOrderTurnover",
                "discountAmountForSit_downOrders",
                "actualAmountReceivedOnSit_downOrder",
                "estimatedProfitFromIn_roomDining",
                "takeawayEstimatedProfit",
                "take_outOrderVolume",
                "numberOfIn_roomOrders",
                "openingDate",
                "closingTime",
                "franchisee",
                "dailyRate",
                "rent",
                "districtsAndCounties",
                "storeActiveStatus",
                "status",
                "labour",
                "break_evenPoint",
                "monthlyOperatingDays",
                "dailyActualIncome",
                "actualMonthDays",
                "whetherTheStoreIsClosedThisYear",
                "shopAddress",
                "cityClass",
                "area",
                "roiClassification",
                "membershipCardOrderTurnover",
                "discountAmountForMembershipCardOrder",
                "membershipCardOrderReceivedAmount",
                "membershipCardOrderQuantity",
                "franchiseeRealName",
                "dailyRentCost",
                "eleMeOrderTurnover",
                "eleMeOrderDiscountAmount",
                "hungryMeOrderReceivedAmount",
                "eleMeOrderQuantity",
                "mtOrderTurnover",
                "mtOrderDiscountAmount",
                "usGroupOrdersReceivedAmount",
                "usGroupOrderQuantity",
                "headOfOperations",
                "privateDomain",
                "agentStatus",
                "averageDailyProfit",
                "paid_inClassification",
                "profitClassification",
                "weightedRoi",
                "lossOrNot",
                "storeClassification",
                "locationClassification",
                "eleMeRating",
                "mtScore",
                "mtStoreId_change",
                "hungryMeStoreId_change",
                "cashRegisterSystem",
                "starRating_e_1",
                "starRating_e_2",
                "starRating_e_3",
                "starRating_e_4",
                "starsRating_e_5",
                "starRating_m_1",
                "starRating_m_2",
                "starRating_m_3",
                "starRating_m_4",
                "starRating_m_5",
                "waimaiShopIdEle",
                "waimaiShopNameEle",
                "waimaiShopIdMt",
                "waimaiShopNameMt",
                "deliveryInterventionTime",
                "newTakeawayStoreJudgment",
                "performanceRange",
                "activityType",
                "shopType",
                "take_outDays",
                "temperatureMax",
                "temperatureMin",
                "immediateConcern",
                "eveningWeather",
                "noonWeather",
                "developmentManager",
                "operationSupervision",
                "keyCity",
                "relocationMark",
//                "eleMeRepurchaseRate",
//                "eleBusinessCirclePeerAverage",
//                "eleBusinessCirclePeerTop10",
//                "usGroupRepurchaseRate",
//                "mtBusinessCirclePeerAverage",
//                "mtBusinessCirclePeerTop10",
                "secondaryPersonInCharge",
                "shoppingMallClassification",
            ];

            $last        = GyDailyDeliveryReportCHModel::query()->orderByDesc("date")->first();
            $lastOrderById        = GyDailyDeliveryReportCHModel::query()->orderByDesc("id")->first();
            if ($last) {
                $this->id = $lastOrderById->id;
               $executeDate = Carbon::createFromDate($last->date)->subDays(7)->format("Y-m-d");
            } else {
                $this->id = 0;
                $executeDate = "2021-01-01";
            }

            $execute     = true;
            $nowDate     = Carbon::now()->format("Y-m-d");
            while ($execute && $executeDate <= $nowDate) {
                $batchInsert = [];
                $this->getOutput()->info(
                    "$executeDate 正在执行...  [内存占用:  " . (memory_get_usage(true) / 1024 / 1024) . "MB ]"
                );

                $shopBusiness = GuanyuanRetryRemote::sourceData(
                    'h98d449754d534b8b990c4e3',
                    'r7e03eab637c04bdb838e887',
                    [
                        [
                            'name'        => '日期',
                            'filterType'  => 'EQ',
                            'filterValue' => [$executeDate]
                        ]
                    ]
                );

                if (empty($shopBusiness["data"]) && $nowDate != $executeDate) {
                    //执行脚本日期 == 拉取观远数据日期 数据为空此时为异常状态
                    throw new \Exception("观远拉取数据异常 [ $executeDate ]");
                }

                $this->getOutput()->info("当天数据量 :  " . count($shopBusiness["data"] ?? []));
                if ($shopBusiness["data"]) {
                    collect($shopBusiness["data"])->each(function ($shopBusinessRow) use (
                        $fields,
                        &$batchInsert
                    ) {
                        $this->id = $this->id + 1;
                        $insert = [
                            "id"        => $this->id,
                            "createdAt" => time()
                        ];
                        collect($shopBusinessRow)->each(function ($value, $key) use ($fields, &$insert, &$batchInsert) {
                            if (isset($fields[$key])) {
                                if ($fields[$key] == "storeCode" && empty($value)) {
                                    $value = 0;
                                }
                                $insert[$fields[$key]] = $value;
                            } else {
                                return false;
                            }
                        });
                        $carbonTime = Carbon::createFromDate($insert["date"]);

                        //增加聚合字段信息
                        $insert["dayGroup"]     = (clone $carbonTime)->format("Y-m-d");
                        $insert["weekGroup"]    = (clone $carbonTime)->startOfWeek()->format("Y-m-d");
                        $insert["monthGroup"]   = (clone $carbonTime)->endOfMonth()->format("Y-m");
                        $insert["quarterGroup"] = (clone $carbonTime)->startOfQuarter()->format("Y-m");
                        $insert["yearGroup"]    = (clone $carbonTime)->startOfYear()->format("Y");

                        array_push($batchInsert, $insert);
                    });

                    if ($batchInsert) {
                        GyDailyDeliveryReportCHModel::query()->where("date", "=", $executeDate)->delete();
                        collect($batchInsert)->chunk(500)->each(function (Collection $collection) {
                            GyDailyDeliveryReportCHModel::query()->insert($collection->values()->toArray());
                        });
                    }

                    $executeDate = date("Y-m-d", strtotime(" +1 day", strtotime($executeDate)));
                    unset($shopBusiness, $batchInsert);
                } else {
                    $execute = false;
                }
            }



            logInfo("{$this->description} 成功", collect([]), true, false);

        } catch (\Exception $exception) {
            logException("{$this->description} 失败", $exception, null, true, true);
        }

        return 0;
    }
}
